<script setup lang="ts">
import { getGoodsByIdAPI } from '@/services/goods'
import type { GoodsResult } from '@/types/goods'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import ServicePanel from './components/ServicePanel.vue'
import AddressPanel from './components/AddressPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import type { SkuPopupEvent, SkuPopupInstanceType, SkuPopupLocaldata } from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup'
import { computed } from 'vue'
import { postMemberCartAPI } from '@/services/cart'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 存储商品详情数据
const goods = ref<GoodsResult>()
// 存储商品详情轮播图下标数据
const currentIndex = ref(0)
// 控制骨架屏是否加载状态
const isFinish = ref(false)

// 接收父组件传递的页面参数(用于传递id请求商品详情)
const query = defineProps<{
    id: string
}>()

// 获取商品详情信息
const getGoodsByIdData = async () => {
    const res = await getGoodsByIdAPI(query.id)
    goods.value = res.result
    // 处理SKU组件所需的数据格式
    localdata.value = {
        _id: res.result.id,
        name: res.result.name,
        goods_thumb: res.result.mainPictures[0],
        spec_list: res.result.specs.map(v => {
            return {
                name: v.name,
                list: v.values
            }
        }),
        sku_list: res.result.skus.map(v => {
            return {
                _id: v.id,
                goods_id: res.result.id,
                goods_name: res.result.name,
                image: v.picture,
                price: v.price * 100, // 注意: 需乘以100
                stock: v.inventory,
                sku_name_arr: v.specs.map(vv => vv.valueName)
            }
        })
    }
}

// 获取商品详情轮播图下标(使用UniHelper内置的TS类型)
const onChange: UniHelper.SwiperOnChange = (ev) => {
    currentIndex.value = ev.detail!.current
}

// 点击商品轮播图放大事件(参数: 图片url, 图片列表)
const onTapImage = (url: string) => {
    uni.previewImage({
        current: url,
        urls: goods.value!.mainPictures
    })
}

// 获取弹出层组件实例(使用UniHelper内置的TS类型)
const popup = ref<{
    open: (type?: UniHelper.UniPopupType) => void,
    close: () => void
}>()

// 弹出层条件渲染
const popupName = ref<'address' | 'service'>()

// 点击修改弹出层名称(将name传递给条件渲染用于区分选项, 再打开弹出层)
const openPopup = (name: typeof popupName.value) => {
    popupName.value = name
    popup.value?.open()
}

// 组件加载时调用
onLoad(async () => {
    await getGoodsByIdData()
    isFinish.value = true
})

// 控制是否显示SKU组件
const isShowSku = ref(false)
// 设置商品信息(不然报错)
const localdata = ref({} as SkuPopupLocaldata)

// 设置SKU按钮数据类型
enum SkuMode {
    Both = 1,
    Cart = 2,
    Buy = 3
}
// 设置SKU按钮模式
const mode = ref<SkuMode>(1)

// 重新定义打开SKU弹窗按钮模式
const openSkuProup = (val: SkuMode) => {
    // 显示SKU组件、根据传递的字段修改按钮模式
    isShowSku.value = true
    mode.value = val
}

// 获取SKU组件实例(用于计算选中值, 渲染到页面)
const skuPopupRef = ref<SkuPopupInstanceType>()

// 计算被选中的值(SKU组件实例的属性转换为字符串, 取消选中值有bug, 使用trim方法判断)
const selectArrText = computed(() => {
    return skuPopupRef.value?.selectArr?.join(' ').trim() || '请选择商品规格'
})

// 加入购物车事件
// 将参数传递给请求接口, 请求成功则弹窗提示, 并关闭SKU弹窗
const onAddCart = async (ev: SkuPopupEvent) => {
    await postMemberCartAPI({ skuId: ev._id, count: ev.buy_num })
    uni.showToast({ icon: 'success', title: '添加成功' })
    isShowSku.value = false
}

// SKU立即购买事件(将id传递填写订单页) 
const onBuyNow = (ev: SkuPopupEvent) => {
    // 跳转订单页面并传递参数
    uni.navigateTo({ url: `/pagesOrder/create/create?skuId=${ev._id}&count=${ev.buy_num}` })
    // 关闭SKU组件
    isShowSku.value = false
}
</script>

<template>
    <!-- SKU弹窗组件 -->
    <vk-data-goods-sku-popup v-model="isShowSku" :localdata="localdata" :mode="mode" ref="skuPopupRef" @add-cart="onAddCart"
        @buy-now="onBuyNow" add-cart-background-color="#FFA868" buy-now-background-color="#27BA9B" :actived-style="{
            color: '#27BA9B', borderColor: '#27BA9B', backgroundColor: '#E9F8F5',
        }" />
    <scroll-view v-if="isFinish" scroll-y class="viewport">
        <!-- 基本信息 -->
        <view class="goods">
            <!-- 商品主图 -->
            <view class="preview">
                <swiper @change="onChange" circular>
                    <swiper-item v-for="item in goods?.mainPictures" :key="item">
                        <image @tap="onTapImage(item)" mode="aspectFill" :src="item" class="image" />
                    </swiper-item>
                </swiper>
                <view class="indicator">
                    <text class="current">{{ currentIndex + 1 }}</text>
                    <text class="split">/</text>
                    <text class="total">{{ goods?.mainPictures.length }}</text>
                </view>
            </view>

            <!-- 商品简介 -->
            <view class="meta">
                <view class="price">
                    <text class="symbol">¥</text>
                    <text class="number">{{ goods?.price }}</text>
                </view>
                <view class="name ellipsis"> {{ goods?.name }} </view>
                <view class="desc"> {{ goods?.desc }} </view>
            </view>

            <!-- 操作面板 -->
            <view class="action">
                <view class="item arrow">
                    <text class="label">选择</text>
                    <text class="text ellipsis" @tap="openSkuProup(SkuMode.Both)"> {{ selectArrText }} </text>
                </view>
                <view class="item arrow" @tap="openPopup('address')">
                    <text class="label">送至</text>
                    <text class="text ellipsis"> 请选择收获地址 </text>
                </view>
                <view class="item arrow" @tap="openPopup('service')">
                    <text class="label">服务</text>
                    <text class="text ellipsis"> 无忧退 快速退款 免费包邮 </text>
                </view>
            </view>
        </view>

        <!-- 商品详情 -->
        <view class="detail panel">
            <view class="title">
                <text>详情</text>
            </view>
            <view class="content">
                <view class="properties">
                    <!-- 属性详情 -->
                    <view class="item" v-for="item in goods?.details.properties" :key="item.name">
                        <text class="label">{{ item.name }}</text>
                        <text class="value">{{ item.value }}</text>
                    </view>
                </view>
                <!-- 图片详情 -->
                <image mode="widthFix" v-for="item in goods?.details.pictures" :key="item" :src="item" class="image">
                </image>
            </view>
        </view>

        <!-- 同类推荐 -->
        <view class="similar panel">
            <view class="title">
                <text>同类推荐</text>
            </view>
            <view class="content">
                <navigator v-for="item in goods?.similarProducts" :key="item.id" class="goods" hover-class="none"
                    :url="`/pages/goods/goods?id=${item.id}`">
                    <image class="image" mode="aspectFill" :src="item.picture"></image>
                    <view class="name ellipsis">{{ item.name }}</view>
                    <view class="price">
                        <text class="symbol">¥</text>
                        <text class="number">{{ item.price }}</text>
                    </view>
                </navigator>
            </view>
        </view>
        <!-- 用户操作 -->
        <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
            <view class="icons">
                <button class="icons-button"><text class="icon-heart"></text>收藏</button>
                <!-- #ifdef MP-WEIXIN -->
                <button class="icons-button" open-type="contact">
                    <text class="icon-handset"></text>客服
                </button>
                <!-- #endif -->
                <navigator class="icons-button" url="/pages/cart/cartTwo" open-type="navigate">
                    <text class="icon-cart"></text>购物车
                </navigator>
            </view>
            <view class="buttons">
                <view @tap="openSkuProup(SkuMode.Cart)" class="addcart"> 加入购物车 </view>
                <view @tap="openSkuProup(SkuMode.Buy)" class="buynow"> 立即购买 </view>
            </view>
        </view>
    </scroll-view>
    <!-- 骨架屏(APP端有Bug, 暂时无法解决) -->
    <!-- #ifdef MP-WEIXIN || H5 -->
    <PageSkeleton v-else />
    <!-- #endif -->

    <!-- uni-ui 弹出层组件 -->
    <uni-popup ref="popup" type="bottom" background-color="#fff">
        <AddressPanel v-if="popupName === 'address'" @close="popup?.close()" />
        <ServicePanel v-if="popupName === 'service'" @close="popup?.close()" />
    </uni-popup>
</template>

<style lang="scss">
/* H5端默认开启scoped样式隔离, 导致组件基础样式无效 */
@import './components/styles/goods.scss';
</style>